/* ============================================================
 * Part of 'Autostop' project
 * Under GPL license - http://www.gnu.org/licenses/gpl.html
 * (c) 2006 - Autostop team
 */

///\file generatemarkers.c fake distance markers map generator

#include "analyzer.h"
#include <stdio.h>
#include <unistd.h>

/// Print usage information
void usage()
{
	fprintf( stderr,
		"Usage: generatemarkers {v|h} width height marker1 marker2\n"
		"generated map put into stdout\n"
		"args:\n"
		" - marker orientation : single character: 'v' or 'h'\n"
		" - image width : unsigned integer\n"
		" - image height : unsigned integer\n"
		" - marker 1 position [pixels] : unsigned integer\n"
		" - marker 2 position [pixels] : unsigned integer\n"
		);
}

/// generates image - distances map - consisting of 3 zones with values 0, 1 and 2
/// zones are vertical or horizontal, and are separated by markers
///\par orient	- orientation: 'h' or 'v'
///\par w		- image width
///\par h		- image height
///\par m1		- marker 1 postion
///\par m2		- marker 2 position
///\return 0 on success, non-zero otherwise
int generate_markers( char orient, int w, int h, int m1, int m2 )
{
	int x,y;
	pimage_t pimage = 0;

	// crerate image
	pimage = create_image( w, h );
	if ( ! pimage )
	{
		fprintf( stderr, "Could not create image\n" );
		return 1;
	}

	if ( orient == 'v' )
	{
		for( y = 0; y< h; y++ )
		{
			for( x = 0; x< w; x++ )
			{
				if ( x < m1 )
					image_pixel( pimage, x, y ) = 0;
				else if ( x < m2 )
					image_pixel( pimage, x, y ) = 1;
				else 
					image_pixel( pimage, x, y ) = 2;
			}
		}
	}
	else if ( orient == 'h' )
	{
		for( y = 0; y< h; y++ )
		{
			for( x = 0; x< w; x++ )
			{
				if ( y < m1 )
					image_pixel( pimage, x, y ) = 0;
				else if ( y < m2 )
					image_pixel( pimage, x, y ) = 1;
				else 
					image_pixel( pimage, x, y ) = 2;
			}
		}
	}
	else
	{
		free_image( pimage );
		fprintf( stderr, "Unknown orientation: %c\n", orient );
		return 2; // unknown orientation
	}

	// write image to stdout
	if ( save_image( stdout, pimage ) )
	{
		free_image( pimage );
		fprintf( stderr, "Error writing image\n");
		return 3;
	}

	// free
	free_image( pimage );
	
	return 0;
}

/// Main entry point
int main( int argc, char** argv )
{
	int w = 0;
	int h = 0;
	int m1 = 0;
	int m2 = 0;;
	char orient = 0;

	// check param num
	if ( argc < 6 )
	{
		usage();
		return 1;
	}
	
	// get'n'check orientation
	orient = argv[1][0];
	if ( orient != 'v' && orient != 'h' )
	{
		usage();
		return 1;
	}

	// get integers
	w = atoi( argv[2] );
	h = atoi( argv[3] );
	m1 = atoi( argv[4] );
	m2 = atoi( argv[5] );

	if ( w <= 0 || h <= 0 || m1 <= 0 || m2 <= 0 )
	{
		usage();
		return 1;
	}

	return generate_markers( orient, w, h, m1, m2 );
}

// eof

